package com.sr.examination.exam.exercise;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;

import com.sr.examination.R;
import com.sr.examination.exam.common.adapter.NumberCardAdapter;
import com.sr.examination.exam.result.ResultActivity;
import com.sr.examination.net.Net;
import com.tl.commonlibrary.network.ErrorResponse;
import com.tl.commonlibrary.network.RequestListener;
import com.tl.commonlibrary.network.bean.base.BaseBean;
import com.tl.commonlibrary.tool.UIUtils;
import com.tl.commonlibrary.ui.BaseFragmentActivity;
import com.tl.commonlibrary.ui.beans.Answer;
import com.tl.commonlibrary.ui.beans.ExerciseBean;
import com.tl.commonlibrary.ui.beans.ExerciseListBean;
import com.tl.commonlibrary.ui.widget.CustomAlertDialog;

import java.util.ArrayList;

import retrofit2.Call;

/**
 * Created by JongSung on 18/2/13.
 * 题卡
 */

public class NumberCardActivity extends BaseFragmentActivity implements AdapterView.OnItemClickListener {
    public static void start(Activity context, ExerciseListBean exerciseListBean, String title, long examId, int requestCode) {
        Intent starter = new Intent(context, NumberCardActivity.class);
        starter.putExtra("exerciseListBean", exerciseListBean);
        starter.putExtra("examTitle", title);
        starter.putExtra("examId", examId);
        context.startActivityForResult(starter, requestCode);
    }

    private GridView singleChoiceGView, multipleChoiceGView, judgementChoiceGView, subjectiveGView, caseAnalysisGView, calculationGView, inTrayGView;
    private ExerciseListBean exerciseListBean;
    private ArrayList<ExerciseBean> singleChoiceBeans, multipleChoiceBeans, judgementChoiceBeans, shortAnswerBeans, caseAnalysisBeans, calculationBeans, inTrayBeans;
    private NumberCardAdapter singleChoiceAdapter, multipleChoiceAdapter, judgementChoiceAdapter, shortAnswerAdapter, caseAnalysisAdapter, calculationAdapter, inTrayAdapter;

    private CustomAlertDialog submitDialog;
    private String examTitle;
    private long examId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_number_card);
        exerciseListBean = (ExerciseListBean) getIntent().getSerializableExtra("exerciseListBean");
        if (exerciseListBean == null) {
            UIUtils.showToast(getString(R.string.hint_not_find_number_card));
            finish();
            return;
        }
        examTitle = getIntent().getStringExtra("examTitle");
        examId = getIntent().getLongExtra("examId", 0);
        setTitle(getString(R.string.number_card));
        showLoading();
        singleChoiceGView = findViewById(R.id.singleChoiceGView);
        multipleChoiceGView = findViewById(R.id.multipleChoiceGView);
        judgementChoiceGView = findViewById(R.id.judgementChoiceGView);
        subjectiveGView = findViewById(R.id.subjectiveGView);
        caseAnalysisGView = findViewById(R.id.caseAnalysisGView);
        calculationGView = findViewById(R.id.calculationGView);
        inTrayGView = findViewById(R.id.inTrayGView);

        findViewById(R.id.containerLayout).setVisibility(View.GONE);
        findViewById(R.id.operatorLayout).setVisibility(View.GONE);
        categoryNumberCard();
    }

    private void initData() {
        int start = 0;
        if (singleChoiceBeans != null && !singleChoiceBeans.isEmpty()) {
            singleChoiceAdapter = new NumberCardAdapter(context, singleChoiceBeans).setStart(start);
            singleChoiceAdapter.setClickable(true);
            singleChoiceGView.setOnItemClickListener(this);
            singleChoiceGView.setAdapter(singleChoiceAdapter);
            start += singleChoiceBeans.size();
        } else {
            findViewById(R.id.singleChoiceLayout).setVisibility(View.GONE);
        }
        if (multipleChoiceBeans != null && !multipleChoiceBeans.isEmpty()) {
            multipleChoiceAdapter = new NumberCardAdapter(context, multipleChoiceBeans).setStart(start);
            multipleChoiceAdapter.setClickable(true);
            multipleChoiceGView.setOnItemClickListener(this);
            multipleChoiceGView.setAdapter(multipleChoiceAdapter);
            start += multipleChoiceBeans.size();
        } else {
            findViewById(R.id.multipleChoiceLayout).setVisibility(View.GONE);
        }
        if (judgementChoiceBeans != null && !judgementChoiceBeans.isEmpty()) {
            judgementChoiceAdapter = new NumberCardAdapter(context, judgementChoiceBeans).setStart(start);
            judgementChoiceAdapter.setClickable(true);
            judgementChoiceGView.setOnItemClickListener(this);
            judgementChoiceGView.setAdapter(judgementChoiceAdapter);
            start += judgementChoiceBeans.size();
        } else {
            findViewById(R.id.judgementChoiceLayout).setVisibility(View.GONE);
        }
        if (shortAnswerBeans != null && !shortAnswerBeans.isEmpty()) {
            shortAnswerAdapter = new NumberCardAdapter(context, shortAnswerBeans).setStart(start);
            shortAnswerAdapter.setClickable(true);
            subjectiveGView.setOnItemClickListener(this);
            subjectiveGView.setAdapter(shortAnswerAdapter);
            start += shortAnswerBeans.size();
        } else {
            findViewById(R.id.subjectiveLayout).setVisibility(View.GONE);
        }
        if (caseAnalysisBeans != null && !caseAnalysisBeans.isEmpty()) {
            caseAnalysisAdapter = new NumberCardAdapter(context, caseAnalysisBeans).setStart(start);
            caseAnalysisAdapter.setClickable(true);
            caseAnalysisGView.setOnItemClickListener(this);
            caseAnalysisGView.setAdapter(caseAnalysisAdapter);
            start += caseAnalysisBeans.size();
        } else {
            findViewById(R.id.caseAnalysisLayout).setVisibility(View.GONE);
        }
        if (calculationBeans != null && !calculationBeans.isEmpty()) {
            calculationAdapter = new NumberCardAdapter(context, calculationBeans).setStart(start);
            calculationAdapter.setClickable(true);
            calculationGView.setOnItemClickListener(this);
            calculationGView.setAdapter(calculationAdapter);
            start += calculationBeans.size();
        } else {
            findViewById(R.id.calculationLayout).setVisibility(View.GONE);
        }
        if (inTrayBeans != null && !inTrayBeans.isEmpty()) {
            inTrayAdapter = new NumberCardAdapter(context, inTrayBeans).setStart(start);
            inTrayAdapter.setClickable(true);
            inTrayGView.setOnItemClickListener(this);
            inTrayGView.setAdapter(inTrayAdapter);
            start += inTrayBeans.size();
        } else {
            findViewById(R.id.inTrayLayout).setVisibility(View.GONE);
        }
        findViewById(R.id.containerLayout).setVisibility(View.VISIBLE);
        if (exerciseListBean.isMethodExamination()) {
            findViewById(R.id.operatorLayout).setVisibility(View.VISIBLE);
            findViewById(R.id.finishedBtn).setOnClickListener(this);
        }
    }

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == HANDLER_CATEGORY_START) {
                showLoading();
            } else if (msg.what == HANDLER_CATEGORY_SUCCESS) {
                initData();
                dismissLoading();
            } else if (msg.what == HANDLER_CATEGORY_FAILED) {
                dismissLoading();
            }
            return false;
        }
    });
    private static final int HANDLER_CATEGORY_START = 0;
    private static final int HANDLER_CATEGORY_SUCCESS = 1;
    private static final int HANDLER_CATEGORY_FAILED = 2;

    private void categoryNumberCard() {
        handler.sendEmptyMessage(HANDLER_CATEGORY_START);
        new Thread(new Runnable() {
            @Override
            public void run() {
                ArrayList<ExerciseBean> exerciseBeans = exerciseListBean.getPaperItems();
                if (exerciseBeans != null && !exerciseBeans.isEmpty()) {
                    for (ExerciseBean tempBean : exerciseBeans) {
                        if (tempBean != null) {
                            if (tempBean.isSingleChoose()) {
                                if (singleChoiceBeans == null) {
                                    singleChoiceBeans = new ArrayList<>();
                                }
                                singleChoiceBeans.add(tempBean);
                            } else if (tempBean.isMultipleChoose()) {
                                if (multipleChoiceBeans == null) {
                                    multipleChoiceBeans = new ArrayList<>();
                                }
                                multipleChoiceBeans.add(tempBean);
                            } else if (tempBean.isJudgementChoose()) {
                                if (judgementChoiceBeans == null) {
                                    judgementChoiceBeans = new ArrayList<>();
                                }
                                judgementChoiceBeans.add(tempBean);
                            } else if (tempBean.isShortAnswer()) {
                                if (shortAnswerBeans == null) {
                                    shortAnswerBeans = new ArrayList<>();
                                }
                                shortAnswerBeans.add(tempBean);
                            }else if (tempBean.isCaseAnalysis()) {
                                if (caseAnalysisBeans == null) {
                                    caseAnalysisBeans = new ArrayList<>();
                                }
                                caseAnalysisBeans.add(tempBean);
                            }else if (tempBean.isCalculation()) {
                                if (calculationBeans == null) {
                                    calculationBeans = new ArrayList<>();
                                }
                                calculationBeans.add(tempBean);
                            }else if (tempBean.isInTray()) {
                                if (inTrayBeans == null) {
                                    inTrayBeans = new ArrayList<>();
                                }
                                inTrayBeans.add(tempBean);
                            }
                        }
                    }
                    handler.sendEmptyMessage(HANDLER_CATEGORY_SUCCESS);
                } else {
                    handler.sendEmptyMessage(HANDLER_CATEGORY_FAILED);
                }
            }
        }).start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.finishedBtn:
                submitExercise();
                break;
        }
    }

    /**
     * 提交答案
     */
    private void submitExercise() {
        if (submitDialog == null) {
            submitDialog = new CustomAlertDialog(context);
            submitDialog.setContent(getString(R.string.dialog_submit_exercise));
            submitDialog.setLeftText(getString(R.string.submit_exercise_check_again));
            submitDialog.setRightText(getString(R.string.submit_exercise_submit));
            submitDialog.setListener(new CustomAlertDialog.OnAlertClickListener() {
                @Override
                public void onRightClicked(View view) {
                    ArrayList<Answer> answers = null;
                    if (exerciseListBean != null && exerciseListBean.getPaperItems() != null) {
                        ArrayList<ExerciseBean> exerciseBeans = exerciseListBean.getPaperItems();
                        if (!exerciseBeans.isEmpty()) {
                            Answer answer;
                            answers = new ArrayList<>();
                            for (ExerciseBean temp : exerciseBeans) {
                                if (temp != null) {
                                    if (temp.hasAnswer()) {
                                        answer = new Answer();
                                        answer.answer = temp.getUserAnswer();
                                        answer.itemId = temp.getItemId();
                                        answers.add(answer);
                                    }
                                }
                            }
                        }
                    }
                    if (answers != null) {
                        ExerciseListBean.endTime(context);
                        showProgressDialog(getString(R.string.progress_submit_exercise), false);
                        Net.submitExercise(exerciseListBean.getpUserSummaryId(), answers, new RequestListener<BaseBean<ExerciseListBean>>() {
                            @Override
                            public void onSuccess(Call<BaseBean<ExerciseListBean>> call, BaseBean<ExerciseListBean> response) {
                                if (response.isSuccessful()) {
                                    //提交答案后跳转到结果页，并结束题卡和考试界面
                                    ResultActivity.start(context, examTitle, examId, response.data);
                                    Intent intent = new Intent();
                                    intent.putExtra("finish", true);
                                    setResult(RESULT_OK, intent);
                                    dismissAll();
                                    finish();
                                } else {
                                    dismissAll();
                                }
                            }

                            @Override
                            public void onFailed(Call<BaseBean<ExerciseListBean>> call, ErrorResponse errorResponse) {
                                dismissAll();
                            }
                        });
                    } else {
                        UIUtils.showToast(getString(R.string.hint_submit_exercise_exception));
                    }
                }

                @Override
                public void onLeftClicked(View view) {

                }
            });
        }
        submitDialog.show();
    }

    @Override
    public void onFragmentTrigger(int tag, Bundle bundle) {

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (submitDialog != null) {
            submitDialog.dismiss();
            submitDialog = null;
        }
    }
}
